<template>
  <div class="app-container" v-loading="listLoading">
    <h2>project: {{ listQuery.project }}</h2>
      <el-button  type="warning" @click="addRankTab">新增段位</el-button>

      <div class="stage-clone-setting">
        <span>from</span>
        <el-select v-model="stage_clone.from_name">
          <el-option v-for="item in rank_config.rank_tabs"
            :key="item.name" :label="item.title" :value="item.name"></el-option>
        </el-select>

        <span>克隆到</span>
        <el-select v-model="stage_clone.to_name">
          <el-option key="-1" label="新段位" value="-1"></el-option>
          <el-option v-for="item in rank_config.rank_tabs"
            :key="item.name" :label="item.title" :value="item.name"
            :disabled="item.name === stage_clone.from_name"></el-option>
        </el-select>

        <el-button type="warning" @click="cloneStageRank">确认克隆</el-button>
      </div>

      <el-tabs
        v-model="cur_stage" @tab-click="changeRank"
        type="card" editable
        @tab-remove="removeRankTab">
        <el-tab-pane v-for="item in rank_config.rank_tabs" :key="item.name" :label="item.title" :name="item.name"></el-tab-pane>
      </el-tabs>

      <el-form :model="rank" label-width="250px" :inline="true" >
        <div v-if="event_type === 0 ">
          <el-form-item label="联盟礼物等级from" >
              <el-input v-model.number="rank.condition[0]"></el-input>
            </el-form-item>

            <el-form-item label="联盟礼物等级to">
              <el-input v-model.number="rank.condition[1]"></el-input>
            </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="主城等级范围from" >
              <el-input v-model.number="rank.condition[0]"></el-input>
            </el-form-item>

            <el-form-item label="主城等级范围to">
              <el-input v-model.number="rank.condition[1]"></el-input>
            </el-form-item>
        </div>
      </el-form>

      <div class="draggable" v-if="event_type != 0">
      <el-table style="width: 60%; margin-left: 250px" :data="rank.rank_reward" border fit highlight-current-row row-key="idx">

        <el-table-column align="center" label="idx" width="100">
          <template slot-scope="scope">
            <span>{{ scope.$index+1 }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="from" width="120">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.from"></el-input>
          </template>
        </el-table-column>

        <el-table-column align="center" label="to" width="120">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.to"></el-input>
          </template>
        </el-table-column>

        <el-table-column align="center" label="奖励配置">
          <template slot-scope="scope">
              <component
              :is="page"
              v-if="open_reward"
              :bonus_list.sync="scope.row.reward"
              :from_reward_type_list="from_reward_type_list"
              :from_reward_list="from_reward_list"
              />
         </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="cloneRankReward(scope.row)">克隆</el-button>
            <el-button size="mini" type="danger" @click="deleteRankReward(scope.$index)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      </div>

      <div class="reward_button-setting" style="margin-top: 20px;" v-if="event_type != 0">
        <el-button type="success" @click="addRankReward">新 增</el-button>
      </div>

      <el-button style="margin-top: 30px; margin-right: 100px;" type="primary" @click="addGoalTab">新增goal档位</el-button>
      <div class="goal-clone-setting">
        <span>from</span>
        <el-select v-model="goal_clone.from_name">
          <el-option v-for="item in rank_config.goal_tabs"
            :key="item.name" :label="item.title" :value="item.name"></el-option>
        </el-select>

        <span>克隆到</span>
        <el-select v-model="goal_clone.to_name">
          <el-option key="-1" label="新档位" value="-1"></el-option>
          <el-option v-for="item in rank_config.goal_tabs"
            :key="item.name" :label="item.title" :value="item.name"
            :disabled="item.name === goal_clone.from_name"></el-option>
        </el-select>

        <el-button type="warning" @click="cloneGoalRank">确认克隆</el-button>
      </div>
      <el-tabs
        v-model="cur_goal" @tab-click="changeGoalTab"
        type="card" editable
        @tab-remove="removeGoalTab">
        <el-tab-pane v-for="item in rank_config.goal_tabs" :key="item.name" :label="item.title" :name="item.name"></el-tab-pane>
      </el-tabs>

      <div class="draggable">
      <el-table style="width: 60%; margin-left: 250px" :data="rank.goal[cur_goal]" border fit highlight-current-row v-if="rank.goal"
       ref="dragTable" row-key="idx"
      >

        <el-table-column align="center" label="idx" width="100">
            <template slot-scope="scope">
              <span>{{ scope.$index+1 }}</span>
            </template>
        </el-table-column>

        <el-table-column align="center" label="goal值" width="120">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.to"></el-input>
          </template>
        </el-table-column>

        <el-table-column align="center" label="奖励配置">
          <template slot-scope="scope">
              <component
              :is="page"
              v-if="open_reward"
              :bonus_list.sync="scope.row.reward"
              :from_reward_type_list="from_reward_type_list"
              :from_reward_list="from_reward_list"
              />
         </template>
        </el-table-column>

<!--        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="cloneGoalReward(scope.row)">克隆</el-button>
            <el-button size="mini" type="danger" @click="deleteGoalReward(scope.$index)">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <!-- <el-button style="margin-top: 20px; margin-right: 100px" type="success" @click="addGoalReward">新增goal奖励</el-button> -->
      </div>
      <el-button style="margin-top: 50px; margin-right: 100px" type="danger" @click="updateRankStage">更 新</el-button>
  </div>
</template>
<script>
import reward from '../components/public_reward_clone';
import { fetchList} from '@/api/index';
import Sortable from 'sortablejs'
import {universal_reward_api_get} from "../api/universal_reward_api";
export default {
  data() {
    return {
      listQuery: {
        'action': 'extreme_user_event_project',
        'project': 0,
        'type': 'index',
        'data': null,
        'cur_stage': 0,
        'clone_to_stage': 0,
      },
      event_type:'',
      rules: {},
      page: reward,
      from_reward_type_list: [],
      from_reward_list: {},
      open_reward: false,
      rank: {
        'condition': [0, 0],
        'rank_reward': [],
        'goal': {}
      },
      rank_config: {
        rank_tabs: [],
        total_rank_group: 0,
        rank_tabIndex: 0,

        goal_tabs:[],
        total_goal_group: 0,
        goal_tabIndex: 0
      },
      cur_stage: '0',
      cur_goal: '0',
      listLoading: true,
      goal_clone: {
        'from_data': [],
        'from_name': '',
        'to_name': '',
      },
      stage_clone: {
        'from_data': {},
        'from_name': '',
        'to_name': '',
      }
    }
  },
  created() {
    this.listQuery.project = this.$route.query.project;
    this.getList(0)
  },
  methods: {
    async getList(num) {
        this.listLoading = true;
        if (num === 0) {
          const rewardObject = await universal_reward_api_get()
          this.from_reward_type_list = rewardObject.rewardTypeList
          this.from_reward_list = rewardObject.rewardList
        };


        this.rank = {
                      'condition': [0, 0],
                      'rank_reward': [],
                      'goal': {}
                    }
        this.rank_config = {
                            "rank_tabs": [],
                            "total_rank_group": 0,
                            "rank_tabIndex": 0,
                            "goal_tabs":[],
                            "total_goal_group": 0,
                            "goal_tabIndex": 0
                          }
        this.listQuery.type = 'rank'
        await fetchList(this.listQuery).then(response => {



          this.rank = response.data.rank_stage;
          this.rank_config.rank_tabs = response.data.rank_tabs;
          this.rank_config.total_rank_group = response.data.total_rank_group;
          this.rank_config.rank_tabIndex = response.data.rank_tabIndex;

          this.rank_config.goal_tabs = response.data.goal_tabs;
          this.rank_config.total_goal_group = response.data.total_goal_group;
          this.rank_config.goal_tabIndex = response.data.goal_tabIndex;

          this.event_type = response.event_type;

          this.initTabs();
          this.listLoading = false;
          this.open_reward = true;
        })
        this.$nextTick(() => {
          this.setSort()
        })
      },
    initTabs() {
      if (this.event_type === 0){
        this.from_reward_type_list = []
        this.from_reward_type_list.push({label: "联盟礼物", name: "联盟礼物", type: 10, value: 10})
      }else{
        for (let i = 0; i < this.from_reward_type_list.length; i++) {
          if(this.from_reward_type_list[i]['value'] === 10){
            this.from_reward_type_list.splice(i, 1);
            return false
          }
        }
      }
    },
    async addRankTab() {
      // 每次新增都发送请求到后端，并生成数据入库
      this.listQuery.type = 'add_rank';
      await fetchList(this.listQuery)
      .then(response => {
        if (response.code === 200) {
          this.$notify({
            title: 'Success',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: response.msg
          });
        }
        }).catch(err => {console.log(err)});
      await this.getList(1);
      return false;
    },
    changeRank() {
      this.listQuery.cur_stage = this.cur_stage;
      this.getList(1);
    },
    removeRankTab(targetName) {
      // 直接和后端交互
      let deleteName = '';
      for (let i=0; i<this.rank_config.rank_tabs.length; i++) {
        let node = this.rank_config.rank_tabs[i];
        if (node.name == targetName) {
          deleteName = node.title;
        };
      };
      this.$confirm('删除 ' + deleteName + ', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listQuery.type = 'delete_rank';
          this.listQuery.cur_stage = String(targetName);
          fetchList(this.listQuery)
          .then(response => {
            if (response.code === 200) {
              this.$notify({
                title: 'Success',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: response.msg
              });
            };
            this.listQuery.cur_stage = this.cur_stage == targetName ? '0' : this.cur_stage;
            this.getList(1)
            }).catch(err => {console.log(err)});
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      return false;
    },
    addGoalTab() {
      let newTabTitle = ++this.rank_config.goal_tabIndex + '';
      this.rank_config.total_goal_group++;
      let newTabName = (this.rank_config.total_goal_group).toString();
      this.rank_config.goal_tabs.push({
          title: `goal-档位 ${newTabTitle}`,
          name: newTabName,
      });
      this.cur_goal = newTabName; // 当前页
      this.$set(this.rank.goal, this.cur_goal, []);
    },
    changeGoalTab() {},
    removeGoalTab(targetName) {
      if (this.rank_config.goal_tabs.length === 1) {
        this.$message({message: '不可删除最后一条', type: 'error',});
        return
      };
      let tabs = this.rank_config.goal_tabs;
      let activeName = this.cur_goal;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      };
      this.cur_goal = activeName;
      this.rank_config.goal_tabs = tabs.filter(tab => tab.name !== targetName);
      this.rank_config.goal_tabs.forEach((item, index) => {
        item.title = `goal-档位 ${index+1}`
      });
      this.rank_config.goal_tabIndex = this.rank_config.goal_tabs.length;
      let last_node = this.rank_config.goal_tabs.at(-1)
      this.rank_config.total_goal_group = Number(last_node.name)
      delete this.rank.goal[targetName]
    },
    addRankReward() {
      this.rank.rank_reward.push({
        'idx': this.rank.rank_reward.length,
        'reward': []
      })
    },
    cloneRankReward(item) {
      let new_item = JSON.parse(JSON.stringify(item));
      new_item.idx = this.rank.rank_reward.length;
      this.rank.rank_reward.push(new_item);
    },
    deleteRankReward(index) {
      this.rank.rank_reward.splice(index, 1)
    },
    addGoalReward() {
      this.rank.goal[this.cur_goal].push({
        'idx': this.rank.goal[this.cur_goal].length,
        "from":1,
        "to":'',
        'reward': []
      })
    },
    cloneGoalReward(item) {
      let new_item = JSON.parse(JSON.stringify(item));
      new_item.idx = this.rank.goal[this.cur_goal].length;
      this.rank.goal[this.cur_goal].push(new_item);
    },
    deleteGoalReward(index) {
      this.rank.goal[this.cur_goal].splice(index, 1)
    },
    updateRankStage() {
      let permit_submit = this.checkData();
      if (!permit_submit) {
        return
      };
      // console.log(this.rank);
      this.listQuery.type = 'update_rank';
      this.listQuery.data = this.rank;
      this.listQuery.cur_stage = this.cur_stage;
      fetchList(this.listQuery)
      .then(response => {
        if (response.code === 200) {
          this.$notify({
            title: 'Success',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: response.msg
          });
        }
        }).catch(err => {console.log(err)})
        return false;
    },
    checkData() {
      for (let i in this.rank.goal) {
        for (let j = 0; j < this.rank.goal[i].length; j++) {
          if (this.rank.goal[i][j]['to'] === undefined || this.rank.goal[i][j]['to'] === '') {
            this.$message({'type': 'warning', 'message': `goal-${i}挡位的goal第${j+1}条配置的goal未填写`});
            return false
          }
          if (this.rank.goal[i][j]['reward'] === undefined || this.rank.goal[i][j]['reward'].length === 0) {
            this.$message({'type': 'warning', 'message': `goal-${i}挡位的goal第${j+1}条配置的奖励未填写`});
            return false
          }
        }
      }
      for (let i = 0; i < this.rank.rank_reward.length; i++) {
        if (this.rank.rank_reward[i]['from'] === undefined || this.rank.rank_reward[i]['from'] === '') {
          this.$message({'type': 'warning', 'message': `rank-${i+1}的from未填写`});
          return false
        }
        if (this.rank.rank_reward[i]['to'] === undefined || this.rank.rank_reward[i]['to'] === '') {
          this.$message({'type': 'warning', 'message': `rank-${i+1}的to未填写`});
          return false
        }
        if (this.rank.rank_reward[i]['reward'] === undefined || this.rank.rank_reward[i]['reward'].length === 0) {
          this.$message({'type': 'warning', 'message': `rank-${i+1}的reward未填写`});
          return false
        }
        if (this.rank.rank_reward[i]['from'] > this.rank.rank_reward[i]['to'] ) {
          this.$message({'type': 'warning', 'message': `rank-${i+1}的from > to`});
          return false
        }
        if (i > 0 && this.rank.rank_reward[i]['from'] != this.rank.rank_reward[i-1]['to'] + 1) {
          this.$message({'type': 'warning', 'message': `rank${i+1}的from不连续`});
          return false
        }
      }
      if (this.rank.condition === undefined || this.rank.condition.length !== 2) {
        this.$message({'type': 'warning', 'message': `等级未填写`});
        return false
      }
      if (this.rank.condition[0] === undefined || this.rank.condition[0] === '') {
        this.$message({'type': 'warning', 'message': `等级From未填写`});
        return false
      }
      if (this.rank.condition[1] === undefined || this.rank.condition[1] === '') {
        this.$message({'type': 'warning', 'message': `等级To未填写`});
        return false
      }



      return true
    },
    cloneGoalRank() {
      this.$confirm('确认克隆?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.goal_clone.to_name === this.goal_clone.from_name) {
            this.$notify({'title': 'Warning', 'type': 'warning', 'message': '不能克隆到相同档位'});
            return
          };
          let from_goal_data = JSON.parse(JSON.stringify(this.rank.goal[this.goal_clone.from_name]));
          if (this.goal_clone.to_name === '-1') {
            // 新档位
            let newTabTitle = ++this.rank_config.goal_tabIndex + '';
            this.rank_config.total_goal_group++;
            let newTabName = (this.rank_config.total_goal_group).toString();
            this.rank_config.goal_tabs.push({
                title: `goal-档位 ${newTabTitle}`,
                name: newTabName,
            });
            // this.cur_goal = newTabName; // 当前页
            this.$set(this.rank.goal, newTabName, from_goal_data);
          } else {
            // 覆盖原有档位
            this.$set(this.rank.goal, this.goal_clone.to_name, from_goal_data);
          };
          this.$notify({
            title: 'Success',
            message: '克隆goal档位成功,需要更新才能生效',
            type: 'success',
            duration: 2000
          })
        }).catch(() => {
          this.$notify({
            title: '取消',
            type: 'info',
            message: '已取消克隆goal档位'
          });
        });
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.rank.goal[this.cur_goal].splice(evt.oldIndex, 1)[0]
          this.rank.goal[this.cur_goal].splice(evt.newIndex, 0, targetRow)
        }
      })
    },
    async cloneStageRank() {
      this.$confirm('确认克隆段位?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.stage_clone.to_name === this.stage_clone.from_name) {
            this.$notify({'title': 'Warning', 'type': 'warning', 'message': '不能克隆到相同段位'});
            return
          };
          // 克隆到新增段位 发送请求到后端，并生成数据入库
          this.listQuery.type = 'clone_rank';
          this.listQuery.cur_stage = Number(this.stage_clone.from_name);
          this.listQuery.clone_to_stage = Number(this.stage_clone.to_name);
          fetchList(this.listQuery)
          .then(response => {
            if (response.code === 200) {
              this.$notify({
                title: 'Success',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: response.msg
              });
            };
            this.getList(1);
            }).catch(err => {console.log(err)});

        }).catch(() => {
          this.$notify({
            title: '取消',
            type: 'info',
            message: '已取消克隆段位'
          });
        });
    },
  }
}
</script>

<style scoped>
.goal-clone-setting {
  margin-top: 20px;
  margin-right: 100px;
}
.stage-clone-setting {
  margin-top: 20px;
  margin-right: 100px;
}
</style>
